// pages/diaryCreate/index.js
const {
  getTodayDate,
  getWeek,
  formatNumber,
  getBarAndTitleHeight,
} = require('../../utils/util')
const api = require('../../config/api')
const env = require('../../config/ali-oss')
const request = require('../../utils/request')
const uploadImage = require('../../utils/UploadAliyun.js')
let app = getApp()
let handleSave = false
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dateTime: '',
    showModalStatus: false,
    years: [],
    months: [],
    days: [],
    hours: [],
    minutes: [],
    isday: true,
    chooseDay: '',
    chooseTime: '',
    diary: {
      authority: '',
      content: '',
      isDraft: 1,
      releaseTime: '',
      patientId: '',
      urlList: [],
    },
    backmodel: false,
    root: {
      key: 1,
      name: '公开',
      desc: '另一位绑定孩子档案的用户可见',
    },
    datePickVal: [],
    timePickVal: [],
    isEndChoose: true, // 是否已结束时间选择滚动
    modalHeight: app.kBottomSafeHeight + 375,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const today = getTodayDate()
    const date = today.year + '-' + today.month + '-' + today.day
    const time = today.hour + ':' + today.minute
    const weekDay = getWeek(date).week
    let [years, months, days, hours, minutes] = [[], [], [], [], []]
    // 初始化日期选择器数据
    for (let i = Number(today.year) - 5; i <= Number(today.year) + 5; i++) {
      years.push(String(i))
    }
    for (let i = 1; i <= 12; i++) {
      months.push(String(i))
    }
    //
    for (let i = 1; i <= 31; i++) {
      days.push(String(i))
    }
    // 初始化时间选择器数据
    for (let i = 1; i <= 24; i++) {
      hours.push(formatNumber(i))
    }
    for (let i = 0; i <= 59; i++) {
      minutes.push(formatNumber(i))
    }
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.statusBarHeight,
        })
      },
    })
    this.setData({
      dateTime: (date + ' ' + time + ' ' + weekDay).replace(/-/g, '/'),
      chooseDay: date,
      chooseTime: time,
      years,
      months,
      days,
      hours,
      minutes,
      ...getBarAndTitleHeight(),
    })
    this.getDraftInfo()
  },
  // 查询草稿
  getDraftInfo: async function () {
    const patientInfo = wx.getStorageSync('patientInfo')
    const requestUrl = patientInfo?.id
      ? `${api.getDraft}?patientId=${patientInfo.id}`
      : api.getDraft
    const res = await request.get(requestUrl, {}, { loading: false })
    if (res.httpStatus === 200 && res.data) {
      const { authority, content, releaseTime, imgList, isDraft } = res.data
      let { diary } = this.data

      diary = {
        authority,
        content,
        releaseTime,
        urlList: imgList,
        isDraft,
      }
      this.setData({
        diary,
      })
      this.rootItem(res.data.authority)
    }
  },
  deleteImg(val) {
    const diary = this.data.diary
    diary.urlList.splice(val.currentTarget.dataset.index, 1)
    this.setData({
      diary,
    })
  },
  //获取月的总天数--数组
  getTotalDayByMonth(year, month) {
    month = parseInt(month, 10)
    let d = new Date(year, month, 0)
    let totalDay = d.getDate()
    let daySource = []
    for (let i = 1; i <= totalDay; i++) {
      daySource.push(String(i))
    }
    return daySource
  },
  hideModal() {
    this.setData({
      showModalStatus: false,
      backmodel: false,
    })
  },
  startChoose() {
    this.setData({
      isEndChoose: false,
    })
  },
  endChoose(e) {
    this.setData({
      isEndChoose: true,
    })
  },
  // 日记内容
  diaryContent(e) {
    let { diary } = this.data
    diary.content = e.detail.value
    this.setData({
      diary,
    })
  },
  // 上传图片
  upLoadImg: async function () {
    const that = this
    const length = that.data.diary.urlList.length
    wx.chooseImage({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      count: 9 - length,
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        for (let i in tempFilePaths) {
          //显示消息提示框
          that.uploadimg(tempFilePaths[i])
        }
      },
    })
  },

  uploadimg: function (data) {
    const that = this
    uploadImage({
      dir: 'zhiliao-applet/',
      filePath: data,
      // voucher: voucher.data,
      success: function (res) {
        let pic_url = env.uploadImageUrl + '/' + res
        console.log('pic_url',pic_url);
        const diary = that.data.diary
        diary.urlList.push(pic_url)
        that.addFile(pic_url)
        that.setData({
          diary,
        })
      },
      fail: function (e) {
        //图片上传失败，图片上传失败的变量+1
        wx.showToast({
          title: 'oss上传失败！',
        })
        that.setData({
          returnBack: true,
          photo: null,
        })
        wx.hideLoading()
      },
    })
  },
  addFile: async function (imgUrl) {
    const res = await request.post(api.addFile, { imgUrl })
  },
  // 新增日记
  saveBtn: async function (val) {
    if (handleSave) {
      return
    }
    handleSave = true
    const key = val.currentTarget.dataset.key
    const { root, diary, chooseDay, chooseTime } = this.data

    let chooseDayF = chooseDay.replace(/\//g, '-')

    const patientInfo = wx.getStorageSync('patientInfo')
    diary.authority = root.key
    // if (diary.releaseTime.length !== 19) {
    // 	diary.releaseTime = chooseDay + ' ' + chooseTime + ':00'
    // }

    let releaseTime = chooseDayF + ' ' + chooseTime
    if (releaseTime.length !== 19) {
      releaseTime = releaseTime + ':00'
    }

    diary.releaseTime = releaseTime

    diary.patientId = patientInfo.id
    if (key === 'save') {
      diary.isDraft = 0
    } else {
      diary.isDraft = 1
    }
    const res = await request.post(api.createDiary, diary)
    if (res.httpStatus === 200) {
      if (key === 'save') {
        wx.navigateTo({
          url: `/pages/diaryDetail/index?diaryId=${res.data}&isCreate=create`,
        })
      } else {
        this.back()
      }
      setTimeout(() => {
        handleSave = false
      }, 1000)
    } else {
      this.setData({
        backmodel: false,
      })
      setTimeout(() => {
        handleSave = false
      }, 1000)
    }
  },
  // 自定义返回
  goBack() {
    const { content, urlList } = this.data.diary
    if (content || urlList.length > 0) {
      this.setData({
        backmodel: true,
      })
    } else {
      this.back()
    }
  },
  back() {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 显示分享弹窗
  showRootSheet() {
    this.rootSheet.show()
  },
  // 隐藏分享弹窗
  hideRootSheet() {
    this.rootSheet.hide()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.rootSheet = this.selectComponent('#rootSheet')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1]
    const id = Number(currPage.__data__.chooseRoot)
    this.rootItem(id)
  },
  // 修改权限
  chooseRoot(e) {
    const id = e.currentTarget.dataset.id
    this.rootItem(Number(id))
    this.rootSheet.hide()
  },
  rootItem(id) {
    if (id === 1) {
      this.setData({
        root: {
          key: 1,
          name: '公开',
          desc: '另一位绑定孩子档案的用户可见',
        },
      })
    }
    if (id === 2) {
      this.setData({
        root: {
          key: 2,
          name: '私密',
          desc: '仅自己可见',
        },
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
